<!-- Copyright (c) 2022 渝州大数据实验室
 *
 * Lanius is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *
 *     http://license.coscl.org.cn/MulanPSL2
 *
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
-->
<!-- 
* @desc:账号新增弹窗
* @fileName:Operation.vue
* @author:chenxiaofeng@yzbdl.ac.cn
* @date:2022-4-15
!-->
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import type { FormInstance } from "element-plus";
import { Delete as deleteIcon } from "@element-plus/icons-vue";
import { checkPassword, encryptAes } from "@/services/common/tool";
// 接受父组件传回
const props = defineProps({
  // 角色下拉下拉值
  roleList: Array as any,
  saveUser: Function as any,
  editUser: Function as any,
  oneUserInfo: Object as any,
  tableOrgData: Array as any,
  // 新增或修改标识
  addOrEdit: String,
});

const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
let ruleForm: any = reactive({
  userName: "",
  password: "",
  nickName: "",
  userOrg: [{ orgId: "", chief: "" }] as unknown as IOrgItem[],
});
const labelPosition = ref("top");

/**
 * @description: 密码验证正则
 * @param {any} rule
 * @param {any} value
 * @param {any} callback
 * @return void
 */
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else if (!checkPassword(value)) {
    callback(
      new Error("密码必须包含英文大小写，数字，特殊字符，字符数量为6-20位")
    );
  } else {
    callback();
  }
};

interface IOrgItem {
  orgId: string;
  chief: string | boolean;
}

/**
 * @description: 删除一行组织
 * @param {number} index
 * @return void
 */
const delOrgItem = (index: number) => {
  ruleForm.userOrg.splice(index, 1);
};

/**
 * @description: 添加一行组织
 * @return void
 */
const addOrgItem = () => {
  let orgItemJson: IOrgItem = { orgId: "", chief: "" };
  ruleForm.userOrg.push(orgItemJson);
};

//定义校验规则
const rules = reactive({
  userName: [{ required: true, message: "请输入用户账号", trigger: "blur" }],
  password: [{ validator: validatePass, required: true, trigger: "blur" }],
  nickName: [{ required: true, message: "请输入用户昵称", trigger: "blur" }],
});

/**
 * @description: 提交表单
 * @param {FormInstance | undefined} formEl
 * @return void
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (props.addOrEdit === "新增") {
        let saveObj: any = {
          password: encryptAes(ruleForm.password),
          userName: ruleForm.userName,
          nickName: ruleForm.nickName,
        };
        if (ruleForm.userOrg.length > 0) {
          if (
            ruleForm.userOrg[0].chief !== "" ||
            ruleForm.userOrg[0].orgId !== ""
          ) {
            saveObj.userOrg = ruleForm.userOrg;
          }
        }
        props.saveUser(saveObj);
      } else {
        // 修改
        let saveObj: any = {
          id: props.oneUserInfo.id,
          nickName: ruleForm.nickName,
        };
        if (ruleForm.userOrg.length > 0) {
          if (
            ruleForm.userOrg[0].chief !== "" ||
            ruleForm.userOrg[0].orgId !== ""
          ) {
            saveObj.userOrgRelations = ruleForm.userOrg;
          }
        } else {
          saveObj.userOrgRelations = [];
        }
        props.editUser(saveObj);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

onMounted(() => {
  let userInfo = { ...props.oneUserInfo };
  if (JSON.stringify(userInfo) !== "{}") {
    ruleForm.userName = userInfo.userName;
    ruleForm.password = userInfo.password;
    ruleForm.nickName = userInfo.nickName;
    if (typeof userInfo.relativeOrg !== "undefined") {
      ruleForm.userOrg = userInfo.relativeOrg.map((item: any) => {
        return {
          orgId: item.id,
          chief: item.chief,
        };
      });
    }
  }
});
</script>

<template>
  <div class="operation">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      :label-position="labelPosition"
      label-width="120px"
      class="demo-ruleForm"
      :size="formSize"
    >
      <el-form-item label="用户账号" prop="userName">
        <el-input
          v-model="ruleForm.userName"
          size="large"
          :disabled="props.addOrEdit === '编辑'"
          placeholder="请输入用户账号"
          show-word-limit
          maxlength="64"
        />
      </el-form-item>
      <el-form-item
        label="账号密码"
        prop="password"
        v-if="props.addOrEdit === '新增'"
      >
        <el-input
          v-model="ruleForm.password"
          type="password"
          size="large"
          placeholder="请输入账号密码"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
          v-model="ruleForm.nickName"
          size="large"
          placeholder="请输入用户昵称"
          show-word-limit
          maxlength="64"
        />
      </el-form-item>
      <el-form-item label="组织" prop="org">
        <div
          v-for="(orgItem, index) in ruleForm.userOrg"
          :key="index"
          class="org-list"
        >
          <el-select v-model="orgItem.orgId" class="org-list-w1">
            <el-option
              v-for="orgList in props.tableOrgData"
              :key="orgList.id"
              :label="orgList.orgName"
              :value="orgList.id"
            ></el-option>
          </el-select>
          <el-select v-model="orgItem.chief" class="org-list-w1">
            <el-option label="普通成员" :value="false"></el-option>
            <el-option label="管理员" :value="true"></el-option>
          </el-select>
          <div @click="delOrgItem(index)" class="op-icon">
            <el-icon><delete-icon /></el-icon>
          </div>
        </div>
        <div class="op-icon add" @click="addOrgItem">+</div>
      </el-form-item>
      <el-form-item class="click-button">
        <el-button @click="submitForm(ruleFormRef)">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="scss">
.org-list {
  width: 100%;
  display: flex;
  margin-bottom: 10px;
  .org-list-w1 {
    flex: 1;
    margin-right: 10px;
  }
}
.op-icon {
  border: 1px solid #ccc;
  width: 40px;
  height: 38px;
  text-align: center;
  line-height: 38px;
  cursor: pointer;
  &.add {
    font-size: 22px;
  }
}
:deep(.el-form-item__label) {
  font-family: PingFang SC;
  font-weight: 700;
  color: #000000;
  font-size: 14px;
}
:deep(.el-input) {
  height: 40px;
  background-color: #ffffff;
}
:deep(.el-textarea) {
  height: 100px;
  background-color: #ffffff;
  .el-textarea__inner {
    height: 100px;
  }
}
.click-button {
  :deep(.el-form-item__content) {
    display: flex;
    justify-content: flex-end;
    .el-button {
      height: 40px;
      background-color: #ffffff;
      border: 1px solid;
      border-color: #cccccc;
    }
  }
}
</style>
